package test.enba.nacos.consumer.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import test.enba.nacos.consumer.properties.DemoProperties;

@RestController
@RequestMapping("/nacos")
public class NcosController {

  private final RestTemplate restTemplate;
  private final DemoProperties nacosProperties;

  @Autowired private DiscoveryClient discoveryClient;

  public NcosController(DemoProperties nacosProperties, RestTemplate restTemplate) {
    this.nacosProperties = nacosProperties;
    this.restTemplate = restTemplate;
  }

  // 测试配置读取
  @RequestMapping("/test")
  public String test() {
    return nacosProperties.getName()
        + ":"
        + nacosProperties.getAge()
        + ":"
        + nacosProperties.isFlag();
  }

  // 获取所有注册的服务名称
  @GetMapping("/services")
  public List<String> getServices() {
    List<String> services = discoveryClient.getServices();
    return services;
  }

  // 获取某个服务的实例信息
  @GetMapping("/service-instances")
  public String getServiceInstances() {
    List<ServiceInstance> instances =
        discoveryClient.getInstances("enba-boot-starter-nacos-test-provider");
    return instances.toString();
  }

  // 负载均衡调用服务
  @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET)
  public String echo(@PathVariable String str) {
    return restTemplate.getForObject(
        "http://enba-boot-starter-nacos-test-provider/nacos/echo/" + str, String.class);
  }
}
